<?php

namespace app\admin\controller\auth;

use app\admin\model\Merchant as MerchantModel;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use addons\fzdc\library\Wechat;

/**
 * 角色组
 *
 * @icon   fa fa-group
 * @remark 角色组可以有多个,角色有上下级层级关系,如果子角色有角色组和管理员的权限则可以派生属于自己组别下级的角色组或管理员
 */
class Merchant extends Backend
{
     /**
     * 查看
     */
    
    /**
     *
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new MerchantModel;
    }
       /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
              ->with(['us'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
    /*
        * 生成二维码
        */
        public function generate($ids)
        {
            $type = '1';//默认是店长
            $merchant = \app\admin\model\Merchant::get($ids);
            $wechat = new Wechat('wxMiniProgram');

            if (!$merchant->image){
                $row = [
                    "release"=>$this->appimg($wechat,$merchant,'release',$type),
                    "trial"=>$this->appimg($wechat,$merchant,'trial',$type),
                    "develop"=>$this->appimg($wechat,$merchant,'develop',$type),
                ];
                $merchant->updated_at=date('Y-m-d H:i:s');
                $merchant->image = json_encode($row,true);
                $merchant->save();
            }else{
                $row = json_decode($merchant->image,true);
            }



            $this->assign('row', $row);
            $this->assign('id', $ids);
            return $this->fetch();
        }
        private function appimg($wechat,$sear,$env_version,$type){
        //        var_dump($type);die;
                try {
                    $content = $wechat->getApp()->app_code->getUnlimit($sear['id'].'_'. $type, [
                        'page' => 'pages/merchant/merchant/index',
                        'env_version'=>$env_version,
                        'check_path'=>false,
                    ]);
                    // 生成小程序码到本地
                    $fileName = uniqid(). '.png';
                    $savePath = ROOT_PATH . 'public/uploads/' . 'merchant/';
                    if (!file_exists($savePath)) {
                        //检查是否有该文件夹，如果没有就创建，并给予最高权限
                        mkdir($savePath, 0777, true);
                    }
                    //判断方法是否存在
                    if (!method_exists($content, 'getBody')) {
                        throw new \Exception('获取小程序码失败');
                    }
                    // 保存到文件
                    file_put_contents($savePath . $fileName, $content->getBody());
        
                    return "/uploads/merchant/" . $fileName;
                }catch (\Exception $e){
        //            var_dump($e->getMessage());die;
                    return "";
                }
        
            }
    // public function index()
    // {
    //     $merchantListarray= collection(MerchantModel::where('status',1)->select())->toArray();
    //     $this->view->assign('merchantList', $merchantListarray);
    //     return $this->view->fetch();
    // }
}